package dao;

import javax.faces.context.FacesContext;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;

/**
 *
 * @author CesarFrantz
 */

public class CompraDAO {
    private Session sessao;
    private Transaction trans;
 
    public CompraDAO() {}
    
    public void addCompra(){        
        try {
            Integer idusuario = (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user_id") != null) ? (Integer) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user_id") : '1';
            sessao = HibernateUtil.getSessionFactory().openSession();
            trans = sessao.beginTransaction(); 
            
            double total = (double)sessao.createSQLQuery("SELECT SUM(j.preco) FROM jogo j WHERE j.idjogo in (SELECT idjogo FROM carrinho WHERE idusuario=" + idusuario +")").uniqueResult();                       
            
            sessao.createQuery("DELETE FROM Carrinho c WHERE c.idusuario=" + idusuario).executeUpdate();
            sessao.createSQLQuery("INSERT INTO compra VALUES (null, "+idusuario+","+total+")").executeUpdate();                                    
            trans.commit(); 
            
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            sessao.close();
        }        
    } 
        
}
